package connection

import (
	"api-gateway-core/mapping"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	hessian "github.com/apache/dubbo-go-hessian2"
	"io"
	"net/http"
)

// TODO
type HttpConnection struct {
	HttpStatement *mapping.HttpStatement
	InfoMap       map[string]any
}

func NewHttpConnection(httpStatement *mapping.HttpStatement, infoMap map[string]any) (*HttpConnection, error) {
	return &HttpConnection{HttpStatement: httpStatement, InfoMap: infoMap}, nil
}

func (this *HttpConnection) Execute(ctx context.Context, methodName string, types []string, args []hessian.Object) (resp any, err error) {
	application := this.HttpStatement.Application
	uri := this.HttpStatement.URI
	data, err := json.Marshal(this.InfoMap)
	request, err := http.NewRequest(string(this.HttpStatement.HttpCommandType), fmt.Sprintf("http://%s/%s", application, uri), bytes.NewBuffer(data))
	response, err := http.DefaultClient.Do(request)
	defer response.Body.Close()
	result, err := io.ReadAll(response.Body)
	err = json.Unmarshal(result, &resp)
	return
}
